package com.walle.gatewayserver.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.walle.gatewayserver.base.CodeContant;
import com.walle.gatewayserver.service.ITokenService;
import com.walle.gatewayserver.vo.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Component
public class LogoutFilter extends ZuulFilter {
	@Value("${logout.url}")
	private String logoutUrl;
	@Autowired
	private ITokenService tokenService;
	@Override
	public Object run() throws ZuulException {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		String token = request.getHeader("token");
		String sysType = request.getHeader("sysType");
		
		ApiResult apiResult = null;
		if(StringUtils.isEmpty(token)) {
			apiResult = new ApiResult<>(CodeContant.TOKEN_NULL.getCode(), CodeContant.TOKEN_NULL.getMsg());
		}else if(StringUtils.isEmpty(sysType)) {
			apiResult = new ApiResult<>(CodeContant.SYSTYPE_NULL.getCode(), CodeContant.SYSTYPE_NULL.getMsg());
		}else {
			apiResult = tokenService.logout(token, sysType);
		}
		
		
		ctx.setSendZuulResponse(false);
		ctx.setResponseStatusCode(200);
		ctx.setResponseBody(JSON.toJSONString(apiResult));
		
		return null;
	}

	@Override
	public boolean shouldFilter() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		return request.getRequestURI().equals(logoutUrl);
	}

	@Override
	public int filterOrder() {
		// TODO Auto-generated method stub
		return 1;
	}

	@Override
	public String filterType() {
		// TODO Auto-generated method stub
		return "pre";
	}

}
